package csx.study.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import csx.study.demo.dto.LoginFormDTO;
import csx.study.demo.dto.Result;
import csx.study.demo.dto.UserDTO;
import csx.study.demo.entity.User;
import csx.study.demo.mapper.UserMapper;
import csx.study.demo.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import csx.study.demo.utils.MailUtils;
import csx.study.demo.utils.RegexUtils;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  验证码登录
 * </p>
 *
 * @author csx
 * @since 2025-03-03
 */
@Service
public class UserServiceSessionImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private MailUtils mailUtils;

    //TODO 用AOP简化手机号验证

    /**
     * 发送验证码
     * @param phone
     * @param session
     * @return
     */
    @Override
    public Result sendCode(String phone, HttpSession session) {

        if(RegexUtils.isPhoneInvalid(phone)){
            // 手机号不合法
            return Result.fail("手机号不合法");
        }

        // 合法，生成验证码
        String code=RandomUtil.randomNumbers(6);
        log.debug("验证码为："+code);

        // 用邮箱来模拟短信验证码
        //mailUtils.sendMail("1257150224@qq.com", code);

        //TODO 验证码过期
        // 保存到session
        session.setAttribute("code", code);

        return Result.ok();
    }

    /**
     * 登录
     * @param loginForm
     * @param session
     * @return
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {

        String phone = loginForm.getPhone();

        // 校验手机号
        if(RegexUtils.isPhoneInvalid(phone)){
            // 手机号不合法
            return Result.fail("手机号不合法");
        }

        Object cacheCode=session.getAttribute("code");

        // session中不存在名为"code"的key
        if(cacheCode == null){
            return Result.fail("验证码不存在");
        }

        // session中的验证码与用户输入不匹配
        if(!cacheCode.toString().equals(loginForm.getCode())){
            return Result.fail("验证码错误");
        }

        // 验证码验证成功
        // 确认用户是否已经注册
        User user=lambdaQuery().eq(User::getPhone,phone).one();

        //用户不存在
        if(user == null){
            user = createUserByPhone(phone);
        }

        //保存用户到session
        //创建UserDTO对象，隐藏敏感信息
        session.setAttribute("user",BeanUtil.toBean(user,UserDTO.class));

        return Result.ok();
    }

    /**
     * 创建用户
     * @return
     */
    private User createUserByPhone(String phone) {

        //创建用户
        User user=new User();
        user.setPhone(phone);
        //TODO 密码加密
        user.setPassword(RandomUtil.randomNumbers(6));
        user.setNickName("user_"+RandomUtil.randomString(10));

        //保存用户
        save(user);
        log.debug("创建用户"+user.toString());

        return user;
    }
}
